<?php
declare (strict_types=1);

namespace app\common\controller;

use app\common\model\platform\Platform;
use app\common\model\platform\PlatformAddon;
use app\common\model\User;
use app\common\model\user\UserPermission;
use think\Addons;
use think\App;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\View;
use think\Validate;
use think\helper\Str;
use think\facade\Config;


/**
 * 控制器基础类 OldClass
 *
 * @deprecated 该类将在未来的版本中被移除，请使用 use hiduoke\controller\AddonsController; 代替。
 */
abstract class AddonsController extends BaseController
{
    // 当前插件标识
    protected $name;
    // 插件路径
    protected $addon_path;
    // 视图模型
    /**
     * @var \think\View
     */
    protected $view;
    // 插件配置
    protected $addon_config;
    // 插件信息
    protected $addon_info;
    // 访问类型
    protected $visit_type = "addon";

    // 打开炮灰域名
    protected $open_die_domian = false;

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->checkDieDomain();
        $this->name = $this->getName();
        $this->addon_path = $app->addons->getAddonsPath() . $this->name . DIRECTORY_SEPARATOR;
        $this->addon_config = "addon_{$this->name}_config";
        $this->addon_info = "addon_{$this->name}_info";
        $this->view->config([
            'view_path' => $this->addon_path . 'view' . DIRECTORY_SEPARATOR
        ]);

        // 如果有使用模板布局
        if ($this->layout) {
            $this->view->layout('layout/' . $this->layout);
        }
        Cookie::set("dk_plaid", (string)get_plaid());
        Cookie::set("dk_addon", get_addon());
        $topuid = input('topuid', 0);
        if ($topuid) {
            Cookie::set("dk_topuid", $topuid);
        }
        if (!$this->auth->match($this->notLogin)) {
            $platform_count = (new Platform())->where(['uid' => $this->userInfo['uid'], 'plaid' => get_plaid()])->count();
            //TODO 等待更新 存在平台ID 并且不是管理员 并且不是当前平台所属人
            if (get_plaid() && @$this->userInfo['is_admin'] != 1 && !$platform_count) {
                $permission = UserPermission::where(['uid' => $this->userInfo['uid'], 'plaid' => get_plaid()])->find();
                $addons = $permission['addons'];
                $addon_name = get_addon();
                if ($addon_name && !isset($addons[get_addon()])) {
                     showMessage("当前应用没有权限访问", "error", '/', 403);
                }
            }
        }
    }

    // 初始化
    protected function initialize()
    {
    }

    private function checkDieDomain()
    {
        if ($this->open_die_domian) {
            $domain = getDomain();
            if ($domain['die'] && strpos($domain['die'], $this->request->host()) == false) {
                to($domain['die'] . $this->request->server('REQUEST_URI'));
                exit();
            }
        }
    }

    /**
     * 加载模板输出
     * @param string $template
     * @param array $vars 模板文件名
     * @return false|mixed|string   模板输出变量
     * @throws \think\Exception
     */
    protected function fetch($template = '', $vars = [])
    {
        return $this->view->fetch($template, $vars);
    }


    /**
     * 渲染内容输出
     * @access protected
     * @param string $content 模板内容
     * @param array $vars 模板输出变量
     * @return mixed
     */
    protected function display($content = '', $vars = [])
    {
        return $this->view->display($content, $vars);
    }

    /**
     * 模板变量赋值
     * @access protected
     * @param mixed $name 要显示的模板变量
     * @param mixed $value 变量的值
     * @return $this
     */
    protected function assign($name, $value = '')
    {
        $this->view->assign([$name => $value]);

        return $this;
    }

    /**
     * 初始化模板引擎
     * @access protected
     * @param array|string $engine 引擎参数
     * @return $this
     */
    protected function engine($engine)
    {
        $this->view->engine($engine);

        return $this;
    }

    /**
     * 插件基础信息
     * @return array
     */
    final public function getInfo()
    {
        $info = Config::get($this->addon_info, []);
        if ($info) {
            return $info;
        }

        // 文件属性
        $info = $this->info ?? [];
        // 文件配置
        $info_file = $this->addon_path . 'info.ini';
        if (is_file($info_file)) {
            $_info = parse_ini_file($info_file, true, INI_SCANNER_TYPED) ?: [];
            $_info['url'] = addons_url();
            $info = array_merge($_info, $info);
        }
        Config::set($info, $this->addon_info);

        return isset($info) ? $info : [];
    }

    /**
     * 获取配置信息
     * @param bool $type 是否获取完整配置
     * @return array|mixed
     */
    final public function getConfig($type = false)
    {
        $config = Config::get($this->addon_config, []);
        if ($config) {
            return $config;
        }
        $config_file = $this->addon_path . 'config.php';
        if (is_file($config_file)) {
            $temp_arr = (array)include $config_file;
            if ($type) {
                return $temp_arr;
            }
            foreach ($temp_arr as $key => $value) {
                $config[$key] = $value['value'];
            }
            unset($temp_arr);
        }
        Config::set($config, $this->addon_config);

        return $config;
    }

    /**
     * 获取插件标识
     * @return mixed|null
     */
    final protected function getName()
    {
        $class = get_class($this);
        list(, $name,) = explode('\\', $class);
        $this->request->addon = $name;

        return $name;
    }

    public function url($controller, $action = 'index', $vars = [], $domain = false)
    {
        return $this->addonUrl($this->name, $controller, $action, $vars, $domain);
    }

    public function getAddonConfig($plaid = 0, $addon_name = '')
    {
        $plaid = $plaid ?: get_plaid();
        $addon_name = $addon_name ?: get_addon();
        $platform_addon = PlatformAddon::where(['plaid' => $plaid, 'addon_name' => $addon_name])->findOrEmpty();
        if (!$platform_addon->isEmpty()) {
            return $platform_addon->config;
        } else {
            return [];
        }
    }
}
